package com.quick.proxy.server.handler.visitor;

import com.quick.proxy.core.config.ProxyConfig;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Description: 访问者代理服务器子通道处理程序
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
@Component
@Lazy
public class VisitorProxyServerChildChannelHandler extends ChannelInitializer<SocketChannel> {
    private static final EventExecutorGroup TRANS_GROUP = new DefaultEventExecutorGroup(16);
    private final ProxyConfig proxyConfig;
    private final VisitorProxyServerConnectHandler visitorProxyServerConnectHandler;
    private final VisitorProxyServerProtocolDisposeHandler visitorProxyServerProtocolDisposeHandler;
    private final VisitorProxyServerProtocolEncoder visitorProxyServerProtocolEncoder;
    private final VisitorProxyServerProtocolOutboundHandler visitorProxyServerProtocolOutboundHandler;

    public VisitorProxyServerChildChannelHandler(ProxyConfig proxyConfig, VisitorProxyServerConnectHandler visitorProxyServerConnectHandler, VisitorProxyServerProtocolDisposeHandler visitorProxyServerProtocolDisposeHandler, VisitorProxyServerProtocolEncoder visitorProxyServerProtocolEncoder, VisitorProxyServerProtocolOutboundHandler visitorProxyServerProtocolOutboundHandler) {
        this.proxyConfig = proxyConfig;
        this.visitorProxyServerConnectHandler = visitorProxyServerConnectHandler;
        this.visitorProxyServerProtocolDisposeHandler = visitorProxyServerProtocolDisposeHandler;
        this.visitorProxyServerProtocolEncoder = visitorProxyServerProtocolEncoder;
        this.visitorProxyServerProtocolOutboundHandler = visitorProxyServerProtocolOutboundHandler;
    }

    @Override
    protected void initChannel(SocketChannel arg0) {
        arg0.pipeline().addLast(new IdleStateHandler(proxyConfig.getReaderIdleTime(), proxyConfig.getWriterIdleTime(), proxyConfig.getAllIdleTime(), TimeUnit.SECONDS));
        arg0.pipeline().addLast(visitorProxyServerConnectHandler);
        arg0.pipeline().addLast(new VisitorProxyServerProtocolDecoder());
        arg0.pipeline().addLast(visitorProxyServerProtocolOutboundHandler);
        arg0.pipeline().addLast(visitorProxyServerProtocolEncoder);
        arg0.pipeline().addLast(TRANS_GROUP, this.visitorProxyServerProtocolDisposeHandler);
    }

}
